package com.rico.kok.controller.user;

import com.rico.kok.config.FileDirConfig;
import com.rico.kok.entity.User;
import com.rico.kok.service.UserServiceImpl;
import com.rico.kok.service.interf.UserService;
import com.rico.kok.tool.RandomCreate;
import com.rico.kok.tool.RegisterUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.regex.Pattern;

@Controller
public class RegisterController {
    @Autowired
    UserService userService;
    @Autowired
    JavaMailSenderImpl mailSender;
    @Autowired
    FileDirConfig fileDirConfig;
    @Autowired
    RegisterUtils registerUtils;

    //跳转到注册界面
    @RequestMapping("/register.html")
    public String accRegister() {
        return "register";
    }

    //注册用户
    @PostMapping("/register.htm")
    public String register(User user, String verifyCode, MultipartFile updatePic, HttpSession session, Model model) {
        //校验验证码
        if (session.getAttribute("verifyCode") != null) {
            if (!verifyCode.equals(session.getAttribute("verifyCode").toString())) {
                System.out.println("验证码不正确！");
                setMsg(model, "失败", "注册失败了！", "error");
                return "msg";
            }
            //判断验证码是否过期
            if (!registerUtils.isOutTime("sendtime",session)) {
                setMsg(model, "失败", "验证码过期了！", "error");
                return "msg";
            }
            //判断邮箱是否是收件邮箱
            if (!session.getAttribute("email").toString().equals(user.getUserEmail())) {
                setMsg(model, "失败", "不是发送验证码的邮箱！", "error");
                return "msg";
            }
        } else {
            setMsg(model, "失败", "注册失败了！", "error");
            return "msg";
        }
        //校验邮箱
        if (!verifyEmail(user.getUserEmail())) {
            setMsg(model, "失败", "注册失败了！", "error");
            return "msg";
        }
        //校验邮箱格式
        String pattern = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        if (!Pattern.matches(pattern, user.getUserEmail())) {
            setMsg(model, "失败", "你的邮箱格式有问题！", "error");
            return "msg";
        }
        //校验用户名长度
        if (user.getUserName().length() > 26) {
            setMsg(model, "失败", "你这名字多少有点长。", "error");
            return "msg";
        }
        //校验密码长度
        if (user.getUserPassword().length() > 50) {
            setMsg(model, "失败", "这么长的密码？没必要吧？", "error");
            return "msg";
        }

        //文件上传
        //没文件设置为默认头像
        String filename = "/kok/src/userpic/default/ruoyousuosi.jpg";
        long filesize = updatePic.getSize();
        //控制文件上传的大小 10MB 10*1024*1024
        if (filesize < 1024 * 1024 * 10) {
            String type = updatePic.getOriginalFilename().substring(updatePic.getOriginalFilename().lastIndexOf(".") + 1);
            switch (type) {
                case "png":
                case "jpg":
                case "jpeg":
                    filename = registerUtils.updateFile(updatePic);
                default:
                    break;
            }
        }
        //账户信息写入数据库
        user.setUserImage(filename);
        userService.insertUser(user);

        setMsg(model, "成功", "注册成功了！", "success");
        return "msg";
    }

    //验证邮箱是否注册
    @PostMapping("/verifyEmail.htm")
    @ResponseBody
    public boolean verifyExist(HttpServletRequest request) {
        if (request.getParameter("email") != null) {
            String email = request.getParameter("email");
            return verifyEmail(email);
        }
        return false;
    }


    //注册测试，免于每次都发送邮件，此方法直接在控制台打印出验证码
    public void sendEmailFake(HttpServletRequest request) {
        String checkCode = RandomCreate.generateVerCode();
        request.getSession().setAttribute("verifyCode", checkCode);
        System.out.println(checkCode);
    }

    //验证发送验证码间隔是否超过1分钟
    @PostMapping("/verifySendTime.htm")
    @ResponseBody
    public boolean sendTime(HttpServletRequest request) {
        if (request.getSession().getAttribute("sendtime") != null) {
            Date date = (Date) request.getSession().getAttribute("sendtime");
            int res = RandomCreate.getMinute(date, new Date());
            if (res < 1) {
                return false;
            }
        }
        return true;
    }

    //发送邮箱验证码
    @RequestMapping("/sendEmail.htm")
    @ResponseBody
    public void sendEmail(HttpServletRequest request) {
        //获取邮箱地址
        String userEmail = request.getParameter("email");
        //获取6位数随机数
        String checkCode = RandomCreate.generateVerCode();
        //判断是否发送过验证码
        if (request.getSession().getAttribute("verifyCode") != null) {
            Date sendTime = (Date) request.getSession().getAttribute("sendtime");
            int res = RandomCreate.getMinute(sendTime, new Date());
            if (res < 1) {
                return;
            }
        }
        request.getSession().setAttribute("email", userEmail);
        request.getSession().setAttribute("verifyCode", checkCode);
        request.getSession().setAttribute("sendtime", new Date());
        registerUtils.sendEmail(userEmail, checkCode, mailSender, "email.properties");
    }

    //验证邮箱验证码
    @PostMapping("/verifyCode.htm")
    @ResponseBody
    public String verifyCode(HttpServletRequest request) {
        String code = "";
        if (request.getSession().getAttribute("verifyCode") != null) {
            code = request.getSession().getAttribute("verifyCode").toString();
        }

        if (code == "") {
            return RandomCreate.generateVerCode();
        } else {
            return code;
        }
    }

    //验证邮箱方法
    private boolean verifyEmail(String email) {
        boolean res = userService.verifyEmail(email);
        return res;
    }

    //设置msg消息
    public void setMsg(Model model, String title, String msg, String code) {
        //向msg传值
        model.addAttribute("title", title);
        model.addAttribute("msg", msg);
        model.addAttribute("code", code);
    }

}
